package com.hoshiicloud.as2c.minipro.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.as2c.minipro.dto.MemberAddressDto;
import com.hoshiicloud.as2c.minipro.dto.PlatStoreAddParamDTO;
import com.hoshiicloud.as2c.minipro.dto.PlatStoreDTO;
import com.hoshiicloud.as2c.minipro.dto.StoreRangeCalculationDTO;
import com.hoshiicloud.as2c.minipro.feign.GoodsFeignService;
import com.hoshiicloud.as2c.minipro.feign.UserService;
import com.hoshiicloud.as2c.minipro.param.ExtSpuQueryParam;
import com.hoshiicloud.as2c.minipro.param.PlatStoreQueryParam;
import com.hoshiicloud.as2c.minipro.param.StoreQueryParam;
import com.hoshiicloud.as2c.minipro.vo.CategoryGoodsVo;
import com.hoshiicloud.common.controller.BaseController;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.LBSUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Author:campchen
 * @Date:Created in 下午 06:49 2019/6/26
 * @PACKAGENAME com.hoshiicloud.miniapp.controller
 * @Description
 */
@Slf4j
@RestController
@RequestMapping("/store")
@Api(value = "店铺管理", tags = {"店铺管理相关接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class StoreController extends BaseController {


	// 商品微服务Service
	@Autowired
	private GoodsFeignService goodsFeignService;

	// 用户中心微服务Service
	@Autowired
	private UserService userService;

	/**
	 * 根据经纬度分页查询范围内的店铺列表同时包含商品信息
	 *
	 * @param entity 经度
	 * @return Response<Page < StoreRangeCalculationDTO>>
	 */
	@PostMapping(value = "/storeRangeCalculation")
	@ApiOperation(value = "范围查询分页查询店铺列表", notes = "范围查询分页查询店铺列表", consumes = MediaType.APPLICATION_JSON_VALUE)
	public Response<Page<Map<String, Object>>> StoreRangeCalculation(@RequestBody StoreQueryParam entity) {
		BigDecimal longitudeTemp = new BigDecimal(entity.getLongitude());
		BigDecimal latitudeTemp = new BigDecimal(entity.getLatitude());
		StoreRangeCalculationDTO storeRangeCalculationDto = new StoreRangeCalculationDTO();
		storeRangeCalculationDto.setLongitude(longitudeTemp);
		storeRangeCalculationDto.setLatitude(latitudeTemp);
		storeRangeCalculationDto.setPageNumber(entity.getPageNumber());
		storeRangeCalculationDto.setPageSize(entity.getPageSize());
		Response<Page<Map<String, Object>>> rs = userService.StoreRangeCalculation(storeRangeCalculationDto);
		if (null != rs && rs.getCode() == 200 && null != rs.getData().getRecords()) {
			Random r = new Random();
			rs.getData().getRecords().forEach(item -> {
				// 距离取整数
				String distance = (String) item.get("distance");
				if (!"0".equals(distance)) {
					item.put("distance", distance.substring(0, distance.indexOf(".")));
				}
				ExtSpuQueryParam param = new ExtSpuQueryParam();
				param.setPageNumber(String.valueOf(r.nextInt(20)));
				param.setPageSize("3");
				param.setPlatformid(Long.parseLong((String) item.get("platid")));
				param.setStoreId(Long.parseLong((String) item.get("id")));
				// 给对应店铺加上商品数据
				Response<Page<Map<String, Object>>> goods = goodsFeignService.getSpusWithMiniPrice(param);
				item.put("goods", goods.getData().getRecords());
			});
		}
		if (rs.getData() == null && rs.getCode() != 200) {
			log.error("范围查询分页查询失败，没有数据！");
			rs = Response.failed("范围查询分页查询失败，没有数据");
		}
		return rs;
	}

	@GetMapping(value = "query/{id}")
	@ApiOperation(value = "根据id查询店铺详情", notes = "根据id查询店铺详情", consumes = MediaType.APPLICATION_JSON_VALUE)
	public Response<PlatStoreDTO> StoreRangeCalculation(@PathVariable("id") Long id) {
		Response<PlatStoreDTO> response = userService.queryById(id);
		if (response.getCode() != 200 || response.getData() == null) {
			log.error("根据id查询店铺详情失败，没有数据！");
			return Response.failed("根据id查询店铺详情失败，没有数据！");
		}
		return response;
	}

	/*尚未测试*/
    /*@PostMapping(value = "/save")
    @ApiOperation(value = "新增平台店铺")*/
	public Response save(@RequestBody @Valid PlatStoreAddParamDTO param) {
		Response response = userService.save(param);
		if (response.getCode() != 200 || response.getData() == null) {
			log.error("新增平台店铺失败！");
			return Response.failed("新增平台店铺失败！");
		}
		return response;
	}

	/**
	 * 根据店铺ID获取店铺经营类目
	 *
	 * @param storeId 店铺Id
	 * @return Response<List < Map < String, Object>>>
	 */
	@GetMapping(value = "getCategoriesByStoreId/{storeId}")
	@ApiOperation(value = "根据店铺ID获取店铺经营类目", notes = "根据店铺ID获取店铺经营类目", consumes = MediaType.APPLICATION_JSON_VALUE)
	public Response<List<Map<String, Object>>> getCategoriesByStoreId(@PathVariable("storeId") Long storeId) {
		Response<List<Map<String, Object>>> rs;
		try {
			rs = userService.getCategoriesByStoreId(storeId);
		} catch (Exception e) {
			log.error("根据店铺ID获取店铺经营类目异常" + "[" + e.getMessage() + "]");
			rs = Response.failed("根据店铺ID获取店铺经营类目异常" + "[" + e.getMessage() + "]");
		}
		return rs;
	}

	/**
	 * 返回类目加上商品列表（不分页）
	 *
	 * @param param {
	 *              "pageNumber": "1",
	 *              "pageSize": "5",
	 *              "platformid": 9609977215975480,
	 *              "storeId": 2
	 *              }
	 * @return Response<List < CategoryGoodsVo>>
	 */
	@PostMapping(value = "getCategoryAndGoods")
	@ApiOperation(value = "返回类目加上商品列表", notes = "返回类目加上商品列表", consumes = MediaType.APPLICATION_JSON_VALUE)
	public Response<List<CategoryGoodsVo>> getCategoryAndGoods(@RequestBody ExtSpuQueryParam param) {
		Response<List<CategoryGoodsVo>> rs = new Response<>();
		try {
			Response<List<Map<String, Object>>> categories = userService.getCategoriesByStoreId(param.getStoreId());
			if (null != categories && categories.getCode() == 200 && categories.getData().size() > 0) {
				List<CategoryGoodsVo> data = new ArrayList<>();
				categories.getData().forEach(item -> {
					CategoryGoodsVo vo = new CategoryGoodsVo();
					vo.setCategoryId(Long.parseLong((String) item.get("categoryId")));
					vo.setCategoryName((String) item.get("name"));
					param.setCategoryId(Long.parseLong((String) item.get("categoryId")));
					Response<Page<Map<String, Object>>> goods = goodsFeignService.getSpusWithMiniPrice(param);
					vo.setGoods(goods.getData().getRecords());
					data.add(vo);
				});
				rs.setData(data);
			}
		} catch (Exception e) {
			log.error("根据店铺ID获取店铺经营类目异常" + "[" + e.getMessage() + "]");
			rs = Response.failed("根据店铺ID获取店铺经营类目异常" + "[" + e.getMessage() + "]");
		}
		return rs;
	}

	/**
	 * 计算收货地址是否在店铺配送范围内
	 *
	 * @param params 参数店铺ID和地址ID
	 * @return Response<Boolean>
	 */
	@ApiOperation(value = "计算收货地址是否在店铺配送范围内", notes = "计算收货地址是否在店铺配送范围内", consumes = MediaType.APPLICATION_JSON_VALUE)
	@ApiImplicitParam(name = "params", paramType = "body", examples = @Example({
			@ExampleProperty(value = "{'storeId': 123213, 'addressId': 456789}", mediaType = "application/json")
	}))
	@PostMapping("/addressWithinRange")
	public Response<Boolean> addressWithinRange(@RequestBody Map<String, Object> params) {
		Response<Boolean> rs;
		try {
			// 店铺ID
			Long storeId = (Long) params.get("storeId");
			// 收货地址ID
			Long addressId = (Long) params.get("addressId");
			Response<PlatStoreDTO> storeRs = userService.queryById(storeId);
			Response<MemberAddressDto> addressRs = userService.getAddressById(addressId);
			if (null != storeRs && storeRs.getCode() == 200 && null != storeRs.getData()) {
				if (null != addressRs && addressRs.getCode() == 200 && null != addressRs.getData()) {
					BigDecimal storeLongitude = storeRs.getData().getLongitude();
					BigDecimal storeLatitude = storeRs.getData().getLatitude();
					BigDecimal addressLongitude = addressRs.getData().getLongitude();
					BigDecimal addressLatitude = addressRs.getData().getLatitude();
					Double distance = LBSUtil.getDistanceByLongitudeAndLatitude(storeLongitude.doubleValue(), storeLatitude.doubleValue(), addressLongitude.doubleValue(), addressLatitude.doubleValue());
					if (distance > 2000) {
						rs = Response.data(false);
					} else {
						rs = Response.data(true);
					}
				} else {
					rs = Response.failed("查询收货地址信息失败");
				}
			} else {
				rs = Response.failed("查询店铺信息失败");
			}

		} catch (Exception e) {
			rs = Response.failed("根据店铺ID获取店铺经营类目异常" + "[" + e.getMessage() + "]");
		}
		return rs;
	}

	//根据用户ID返回店铺列表
	@PostMapping(value = "/getStoresByUserId")
	@ApiOperation(value = "根据用户ID返回店铺列表", notes = "根据用户ID返回店铺列表", consumes = MediaType.APPLICATION_JSON_VALUE)
	public Response<Page<PlatStoreDTO>> getStoresByUserId(@RequestBody PlatStoreQueryParam param) {
		Response<Page<PlatStoreDTO>> rs;
		try {
			rs = userService.page(param);
		} catch (Exception e) {
			rs = Response.failed("根据店铺ID获取店铺经营类目异常" + "[" + e.getMessage() + "]");
		}
		return rs;
	}

}
